from contextlib import asynccontextmanager

from fastapi import FastAPI
from tortoise import Tortoise
from starlette.staticfiles import StaticFiles
from pathlib import Path
import logging

# 配置日志记录
# logging.basicConfig(
#     level=logging.DEBUG,  # 设置日志级别
#     format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',  # 日志输出格式
# )

from app.core.exceptions import SettingNotFound
from app.core.init_app import (
    init_data,
    make_middlewares,
    register_exceptions,
    register_routers,
)

try:
    from app.settings.config import settings
except ImportError:
    raise SettingNotFound("未查询到配置文件")


@asynccontextmanager
async def lifespan(app: FastAPI):
    await init_data()
    yield
    # logger = Tortoise.get_connection('default').log
    # logger.setLevel(logging.DEBUG)  # 设置日志级别为 DEBUG
    # console_handler = logging.StreamHandler()
    # console_handler.setLevel(logging.DEBUG)
    # console_handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
    # logger.addHandler(console_handler)
    await Tortoise.close_connections()


def create_app() -> FastAPI:
    app = FastAPI(
        title=settings.APP_TITLE,
        description=settings.APP_DESCRIPTION,
        version=settings.VERSION,
        openapi_url="/openapi.json",
        middleware=make_middlewares(),
        lifespan=lifespan,
        log_config="uvicorn_loggin_config.json",
    )
    register_exceptions(app)
    register_routers(app, prefix="/api_mini")
    register_routers(app, prefix="/api")

    static_folder = Path(__file__).parent / "upload"
    app.mount("/app/upload", StaticFiles(directory=static_folder), name="upload")
    return app


app = create_app()
